<template>
  <div>
    <!-- 操作区 -->
    <el-row type="flex" class="row-bg" justify="space-between">
      <el-col class="title" :span="8">
        <div>
          <!-- 图标 -->
          <img src="../assets/img/box.png" alt="box" />
          <!-- 题目 -->
          <span>后台任务列表</span>
        </div>
      </el-col>
      <el-col :span="16" class="btn-box">
        <el-button
          type="primary"
          size="smalll"
          icon="el-icon-plus"
          @click="addDiaLogVisible = true"
          >新建任务</el-button
        >
        <el-button
          type="success"
          size="small"
          icon="el-icon-video-pause"
          @click="pauseJob"
          >暂停任务</el-button
        >
        <el-button
          type="warning"
          size="small"
          icon="el-icon-video-play"
          @click="startJob"
          >开启任务</el-button
        >
        <el-button
          type="primary"
          size="small"
          icon="el-icon-thumb"
          @click="executeJob"
          >立即执行</el-button
        >
        <el-button
          type="danger"
          size="small"
          icon="el-icon-edit"
          @click="showEditDialog()"
          >修改任务</el-button
        >
        <el-button size="small" icon="el-icon-delete" @click="deleteJob"
          >删除任务</el-button
        >
        <el-button
          type="primary"
          size="small"
          icon="el-icon-refresh-left"
          @click="reflashJob"
          >刷新数据</el-button
        >
      </el-col>
    </el-row>
    <!-- 列表区 -->
    <el-card class="list-box">
      <!-- 用户列表区域 -->
      <el-table
        :data="jobList"
        border
        highlight-current-row
        @current-change="handleJobChange"
      >
        <el-table-column label="选择" width="50">
          <template scope="scope">
            <el-radio :label="scope.row" v-model="currentRow">&nbsp;</el-radio>
          </template>
        </el-table-column>
        <el-table-column label="作业名称" prop="taskName"></el-table-column>
        <el-table-column
          label="分组"
          prop="groupName"
          width="100"
        ></el-table-column>
        <el-table-column
          label="最后执行时间"
          prop="lastRunTime"
        ></el-table-column>
        <el-table-column label="间隔(Cron)" prop="interval"></el-table-column>
        <el-table-column label="状态" width="70">
          <template slot-scope="scope">
            <el-tag type="success" effect="dark" v-if="scope.row.status == 0"
              >正常</el-tag
            >
            <el-tag type="danger" effect="dark" v-if="scope.row.status == 1"
              >暂停</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column label="描述" prop="describe"></el-table-column>
        <el-table-column label="ApiUrl" prop="apiUrl"></el-table-column>
        <el-table-column
          label="请求方式"
          prop="requestType"
          width="70"
        ></el-table-column>
        <el-table-column label="历史记录" width="100">
          <template slot-scope="scope">
            <!-- 获取历史按钮 -->
            <el-button
              type="primary"
              icon="el-icon-position"
              size="mini"
              @click="openHistoryJobInfo(scope.row)"
              >操作</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加任务对话框 -->
    <el-dialog
      title="新建任务"
      :visible.sync="addDiaLogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="120px"
      >
        <el-form-item label="作业名称" prop="taskName">
          <el-input v-model="addForm.taskName"></el-input>
        </el-form-item>
        <el-form-item label="分组" prop="groupName">
          <el-input v-model="addForm.groupName"></el-input>
        </el-form-item>
        <el-form-item label="间隔(Cron)" prop="interval">
          <el-input v-model="addForm.interval"></el-input>
        </el-form-item>
        <el-form-item label="ApiUrl" prop="apiUrl">
          <el-input v-model="addForm.apiUrl"></el-input>
        </el-form-item>
        <el-form-item label="header(Key)" prop="authKey">
          <el-input v-model="addForm.authKey"></el-input>
        </el-form-item>
        <el-form-item label="header(value)" prop="authValue">
          <el-input v-model="addForm.authValue"></el-input>
        </el-form-item>
        <el-form-item label="请求方式" prop="requestType">
          <el-select v-model="addForm.requestType" placeholder="请选择请求方式">
            <el-option label="get" value="get"></el-option>
            <el-option label="post" value="post"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="describe">
          <el-input type="textarea" v-model="addForm.describe"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDiaLogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addJob">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改任务对话框 -->
    <el-dialog
      title="修改任务"
      :visible.sync="editDiaLogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="120px"
      >
        <el-form-item label="作业名称" prop="taskName">
          {{ editForm.taskName }}
        </el-form-item>
        <el-form-item label="分组" prop="groupName">
          {{ editForm.groupName }}
        </el-form-item>
        <el-form-item label="间隔(Cron)" prop="interval">
          <el-input v-model="editForm.interval"></el-input>
        </el-form-item>
        <el-form-item label="ApiUrl" prop="apiurl">
          <el-input v-model="editForm.apiUrl"></el-input>
        </el-form-item>
        <el-form-item label="header(Key)" prop="headerkey">
          <el-input v-model="editForm.authKey"></el-input>
        </el-form-item>
        <el-form-item label="header(value)" prop="headervalue">
          <el-input v-model="editForm.authValue"></el-input>
        </el-form-item>
        <el-form-item label="请求方式" prop="requestmethod">
          <el-select
            v-model="editForm.requestType"
            placeholder="请选择请求方式"
          >
            <el-option label="get" value="get"></el-option>
            <el-option label="post" value="post"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="describe">
          <el-input type="textarea" v-model="editForm.describe"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDiaLogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editJobInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 任务执行历史记录 -->
    <el-dialog
      title="任务历史记录"
      :visible.sync="historyDiaLogVisible"
      width="50%"
      @close="historyDialogClosed"
    >
      <el-button @click="firstJobHistory">首页</el-button>
      <el-button @click="nextJobHistory">下一页</el-button>
      <el-timeline :reverse="reverse">
        <el-timeline-item
          v-for="(activity, index) in activities"
          :key="index"
          :timestamp="activity.beginDate"
        >
          {{ activity.msg }}
        </el-timeline-item>
      </el-timeline>
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  components: {},
  data() {
    return {
      // 获取任务列表的参数对象
      queryInfo: {
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 2,
      },
      jobList: [],
      total: 0,
      // 控制添加任务对话框的显示与隐藏
      addDiaLogVisible: false,
      // 添加任务的表单数据
      addForm: {
        taskName: "",
        groupName: "",
        interval: "",
        apiUrl: "",
        authKey: "",
        authValue: "",
        describe: "",
        requestType: "get",
        lastRunTime: "",
        status: 0,
      },
      // 添加表单的验证规则
      addFormRules: {
        taskName: [
          { required: true, message: "请输入作业名称", trigger: "blur" },
        ],
        groupName: [{ required: true, message: "请输入分组", trigger: "blur" }],
        interval: [
          {
            required: true,
            message: "请请输入间隔(Cron)表达式",
            trigger: "blur",
          },
        ],
        apiUrl: [{ required: true, message: "请输入ApiUrl", trigger: "blur" }],
        requestType: [
          { required: true, message: "请选择请求方式", trigger: "blur" },
        ],
      },
      requestmethodoptions: [
        {
          value: "get",
          label: "get",
        },
        {
          value: "post",
          label: "post",
        },
      ],
      // 控制修改用户对话框的显示与隐藏
      editDiaLogVisible: false,
      // 查询到的用户信息对象
      editForm: {},
      // 修改表单的验证规则对象
      editFormRules: {
        taskName: [
          { required: true, message: "请输入作业名称", trigger: "blur" },
        ],
        groupName: [{ required: true, message: "请输入分组", trigger: "blur" }],
        interval: [
          {
            required: true,
            message: "请请输入间隔(Cron)表达式",
            trigger: "blur",
          },
        ],
        apiUrl: [{ required: true, message: "请输入ApiUrl", trigger: "blur" }],
        requestType: [
          { required: true, message: "请选择请求方式", trigger: "blur" },
        ],
      },
      // 获取被选中的数据
      currentRow: null,
      // 控制历史记录的显示与隐藏
      historyDiaLogVisible: false,
      reverse: false,
      activities: [],
      activitieIndex :1
    };
  },
  computed: {},
  watch: {},
  methods: {
    async getjobList() {
      // 获取任务列表
      await this.$http
        .get("Tasksche/GetJobs",{
        params: this.queryInfo})
        .then((res) => {
          this.jobList = res.data.jobList;
          this.total = res.data.jobCount;
        })
        .catch((err) => {
          this.$message.error("获取任务列表失败！");
        });
    },

    handleJobChange(val) {
      this.currentRow = val;
    },
    // 监听 pagesize 改变的事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
    
      this.getjobList();

    },
    // 监听 页码值 的改变
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getjobList();
   
    },
    // 监听添加用户对话框的关闭事件(重置表单)
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    // 点击按钮，添加新任务
    async addJob() {
        const form = _.cloneDeep(this.addForm)
        form.lastRunTime = null; 
        await this.$http
        .post("Tasksche/Add", form)
        .then((res) => {
          this.getjobList(this.queryInfo);
        })
        .catch((err) => {
          this.$message.error("添加任务失败！");
        });
      // 隐藏添加任务的对话框
      this.addDiaLogVisible = false;
    },
    // 暂停任务
    pauseJob() {
      if (this.currentRow == null) {
        this.$message.error("请选择要暂停的任务！");
        return;
      }
      this.$http
        .post("Tasksche/Pause", this.currentRow)
        .then((res) => {
          this.getjobList();
        })
        .catch((err) => {
          this.$message.error("暂停任务失败！");
        });
    },
    // 开启任务
    startJob() {
      if (this.currentRow == null) {
        this.$message.error("请选择要开启的任务！");
        return;
      }
      this.$http
        .post("Tasksche/Start", this.currentRow)
        .then((res) => {
          this.getjobList(this.queryInfo);
        })
        .catch((err) => {
          this.$message.error("开启任务失败！");
        });
    },
    // 立即执行
    executeJob() {
      if (this.currentRow == null) {
        this.$message.error("请选择要执行的任务！");
        return;
      }
      this.$http
        .post("Tasksche/Run", this.currentRow)
        .then((res) => {
          this.getjobList();
        })
        .catch((err) => {
          this.$message.error("执行任务失败！");
        });
    },
    // 打开修改任务的对话框
    showEditDialog() {
      if (this.currentRow == null) {
        this.$message.error("请选择要修改的任务！");
        return;
      }
      this.editForm = this.currentRow;
      this.editDiaLogVisible = true;
    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    async editJobInfo() {
      await this.$http
        .post("Tasksche/Update", this.editForm)
        .then((res) => {
          this.getjobList();
        })
        .catch((err) => {
          this.$message.error("修改任务失败！");
        });
      this.editDiaLogVisible = false;
    },
    // 删除任务
    deleteJob() {
      if (this.currentRow == null) {
        this.$message.error("请选择要删除的任务！");
        return;
      }
      this.$http
        .post("Tasksche/Remove", this.currentRow)
        .then((res) => {
          this.getjobList();
        })
        .catch((err) => {
          this.$message.error("删除任务失败！");
        });
    },
    // 刷新数据
    reflashJob() {
      this.getjobList();
      this.$message.success("刷新成功！");
    },

    // 获取历史记录
    async getjobhistory(job) {
        await this.$http
        .get("Tasksche/GetRunLog", { params: job })
        .then((res) => {
        res.data.length != 0? this.activities = res.data: this.$message.error("获取任务记录失败！");        
        })
        .catch((err) => {
          this.$message.error("获取任务记录失败！");
        });
    },

    async openHistoryJobInfo(job) {
      job.page = this.activitieIndex;
      await this.getjobhistory(job)
      this.historyDiaLogVisible = true;
    },
    historyDialogClosed() {
        this.activitieIndex = 1;
    },
    // 获取首页历史记录
    async firstJobHistory() {
        this.activitieIndex = 1;
        const job =_.cloneDeep(this.currentRow)
        job.page = this.activitieIndex;
      await this.getjobhistory(job)
    },
    // 获取下一页页历史记录
    async nextJobHistory() {
        this.activitieIndex=this.activitieIndex+1;
        const job =_.cloneDeep(this.currentRow);
        job.page = this.activitieIndex;
        await this.getjobhistory(job);
    },
  },
  created() {
    this.getjobList();
  },
  mounted() {},
  beforeCreate() {},
  beforeMount() {},
  beforeUpdate() {},
  updated() {},
  beforeDestroy() {},
  destroyed() {},
  activated() {},
};
</script>
<style lang='less' scoped>
.btn-box {
  display: flex;
  justify-content: flex-end;
}

.title {
  color: #f55636;
  font-size: 25px;
  font-weight: bold;

  div {
    display: flex;
    align-items: center;
    width: 200px;
    padding-bottom: 5px;
    border-bottom: 3px solid #f00;
    img {
      margin-right: 15px;
    }
  }
}

.list-box {
  margin-top: 20px;
}

.el-select {
  width: 100%;
}
</style>